package com.ay.shardingshere.controller;

import com.ay.shardingshere.mapper.OrderMapper;
import com.ay.shardingshere.mapper.ShardingOrderMapper;
import com.ay.shardingshere.mapper.ShardingSingleOrderMapper;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: ay
 * @Date: 2021/6/24
 * @Description: sharding-jdbc 两库两表操作接口
 **/
@RestController
@RequestMapping("/order/")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShardingOrderMapper shardingOrderMapper;

    @Autowired
    private ShardingSingleOrderMapper shardingSingleOrderMapper;

    /**
     * 生成 随机整数
     * @return
     */
    private long getRandomNum(){
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        return (long) Math.abs(threadLocalRandom.nextInt());
    }

    /**
     * 保存订单信息
     * @return
     */
    @PostMapping
    public String save(){
        orderMapper.save(getRandomNum());
        return "ok";
    }

    /**
     * 更新订单信息
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public String update(@PathVariable Long id){
        orderMapper.update(id);
        return "ok";
    }

    /**
     * 查询订单信息
     * @return
     */
    @GetMapping
    public List<Map<String,Object>> list(@RequestParam(required = false,defaultValue = "90") Integer modulo){
        return orderMapper.list(modulo);
    }


    /**
     * 截断表
     */
    @DeleteMapping
    public String truncateTable(){
        orderMapper.truncateTable();
        shardingOrderMapper.truncateTable();
        shardingSingleOrderMapper.truncateTable();
        return "ok";
    }
}


